<template>
  <Tooltip placement="top">
    <template #title>
      <span>导入</span>
    </template>
    <ImportOutlined @click="handleExport" />
  </Tooltip>
  <BasicModal
    v-bind="$attrs"
    :title="t('导入数据')"
    :okText="t('导入')"
    @register="registerModel"
    @ok="handleSubmit"
    :minHeight="120"
    :width="400"
  >
    <Upload
      accept=".xls,.xlsx"
      :file-list="fileList"
      :remove="handleRemove"
      :before-upload="beforeUpload"
    >
      <a-button> <Icon icon="ant-design:upload-outlined" /> {{ t('选择文件') }} </a-button>
      <span class="ml-4">{{ uploadInfo }}</span>
    </Upload>
    <div class="mt-4">
      <Checkbox v-model:checked="updateSupport">
        <Tooltip placement="bottom" :mouse-enter-delay="1" :overlay-style="{ width: '100px' }">
          <template #title>
            {{ t('如果数据已经存在，更新这条数据。') }}
          </template>
          {{ t('是否更新已经存在的数据') }}
        </Tooltip>
      </Checkbox>
      <a-button @click="handleDownloadTemplate()" type="text">
        <Icon icon="fa:file-excel-o" />
        {{ t('下载模板') }}
      </a-button>
    </div>
    <div class="mt-4">
      {{ t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, unref, computed, ref } from 'vue';
  import { Tooltip, Upload, Checkbox } from 'ant-design-vue';
  import { ImportOutlined } from '@ant-design/icons-vue';
  import { useTableContext } from '../../hooks/useTableContext';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Icon } from '/@/components/Icon';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { downloadByUrl } from '/@/utils/file/download';
  import { importData } from '/@/api/layout/vouch/layVoucher';

  export default defineComponent({
    name: 'ImportSetting',
    components: {
      ImportOutlined,
      Tooltip,
      Upload,
      Checkbox,
      Icon,
      BasicModal,
    },
    setup() {
      const table = useTableContext();
      const getValues = computed(() => {
        return unref(table?.getBindValues) || {};
      });

      const { t } = useI18n('sys.empUser');
      const { showMessage, showMessageModal } = useMessage();

      const fileList = ref([]);
      const updateSupport = ref(false);
      const uploadInfo = ref('');

      const [registerModel, { openModal, setModalProps, closeModal }] = useModal();

      function handleExport() {
        openModal();
      }

      const beforeUpload = (file: never) => {
        fileList.value = [file];
        return false;
      };

      const handleRemove = () => {
        fileList.value = [];
      };

      async function handleDownloadTemplate() {
        const values = unref(getValues);
        const { ctxAdminPath } = useGlobSetting();
        downloadByUrl({
          url: ctxAdminPath + '/common/importTemplate?code=' + values.layoutCode,
          target: '_self',
        });
      }

      function onUploadProgress(progressEvent: ProgressEvent) {
        const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
        if (complete != 100) {
          uploadInfo.value = t('正在导入，请稍后') + ' ' + complete + '%...';
        } else {
          uploadInfo.value = '';
        }
      }

      async function handleSubmit() {
        const values = unref(getValues);
        try {
          if (fileList.value.length == 0) {
            showMessage(t('请选择要导入的数据文件'));
            return;
          }
          setModalProps({ confirmLoading: true });
          const params = {
            file: fileList.value[0],
            updateSupport: updateSupport.value ? '1' : '0',
            code: values.layoutCode,
          };
          const { data } = await importData(params, onUploadProgress);
          showMessageModal({ content: data.message });
          setTimeout(closeModal);
        } catch (error: any) {
          if (error && error.errorFields) {
            showMessage(t('您填写的信息有误，请根据提示修正。'));
          }
          console.log('error', error);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      return {
        handleExport,
        fileList,
        updateSupport,
        uploadInfo,
        getValues,
        t,
        handleSubmit,
        beforeUpload,
        handleRemove,
        handleDownloadTemplate,
        registerModel,
      };
    },
  });
</script>
